import java.util.*;

public class LeetCode1418 {

    public List<List<String>> displayTable(List<List<String>> orders) {
        List<List<String>> ans = new ArrayList<>();
        // 桌号：{餐品 ： 个数}（用于构造内容）
        Map<Integer, Map<String, Integer>> tm = new HashMap<>();
        // 餐品（用于构造 title ）
        Set<String> ts = new HashSet<>();
        for (List<String> order : orders) {
            String t = order.get(1);
            String f = order.get(2);
            Integer tidx = Integer.parseInt(t);
            ts.add(f);
            Map<String, Integer> map = tm.getOrDefault(tidx, new HashMap<>());
            map.put(f, map.getOrDefault(f, 0) + 1);
            tm.put(tidx, map);
        }
        int n = tm.size() + 1;
        int m = ts.size() + 1;

        // 构造 title & 手动排序
        List<String> foods = new ArrayList<>(ts);
        Collections.sort(foods);
        List<String> title = new ArrayList<>();
        title.add("Table");
        title.addAll(foods);
        ans.add(title);
        // 构造内容 & 手动排序
        List<Integer> tables = new ArrayList<>(tm.keySet());
        Collections.sort(tables);
        for (int tidx : tables) {
            Map<String, Integer> map = tm.get(tidx);
            List<String> cur = new ArrayList<>();
            cur.add(tidx + "");
            for (String food : foods) {
                cur.add(map.getOrDefault(food, 0) + "");
            }
            ans.add(cur);
        }
        return ans;
    }

    public List<List<String>> displayTable1(List<List<String>> orders) {
        Set<String> set = new HashSet<>(); // 比 list 快 20ms
        for (List<String> order : orders) {
            set.add(order.get(2));
        }
        List<String> foods = new ArrayList<>(set);
        Collections.sort(foods);
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < foods.size(); i++) {
            map.put(foods.get(i), i);
        }
        String[][] num = new String[501][foods.size()];
        for (List<String> order : orders) {
            int x = Integer.parseInt(order.get(1));
//            int y = foods.indexOf(order.get(2));
            int y = map.get(order.get(2));
            if (num[x][y] == null) {
                for (int i = 0; i < foods.size(); i++) {
                    num[x][i] = "0";
                }
            }
            num[x][y] = Integer.toString(Integer.parseInt(num[x][y]) + 1);
        }
        List<List<String>> m = new ArrayList<>();
        foods.add(0, "Table");
        m.add(foods);
        for (int i = 0; i < 501; i++) {
            if (num[i][0] != null) {
                List<String> t = new ArrayList<>();
                t.add(Integer.toString(i));
                t.addAll(Arrays.asList(num[i]));
                m.add(t);
            }
        }
        return m;
    }
}
